package com.ctshk.rpc.payment.utils.unionpay;

import com.ctshk.common.enums.SystemError;
import com.ctshk.common.utils.Assert;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @BelongsProject: ctshk-cloud
 * @BelongsPackage: com.ctshk.rpc.payment.utils.unionpay
 * @Author: hef
 * @CreateTime: 2021-04-27 10:16
 * @Description: 描述
 */
public class UnionPayUtil {

    private static final String encoding = "UTF-8";

    /**
     * java  数据提交 　　 对数据进行签名
     *
     * @param contentData
     * @return　签名后的map对象
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> signData(Map<String, ?> contentData) {
        Map.Entry<String, String> obj = null;
        Map<String, String> submitFromData = new HashMap<String, String>();
        for (Iterator<?> it = contentData.entrySet().iterator(); it.hasNext(); ) {
            obj = (Map.Entry<String, String>) it.next();
            String value = obj.getValue();
            if (StringUtils.isNotBlank(value)) {
                // 对value值进行去除前后空处理
                submitFromData.put(obj.getKey(), value.trim());
                System.out.println(obj.getKey() + "-->" + String.valueOf(value));
            }
        }
        /**
         * 签名
         */
        SDKUtil.sign(submitFromData, encoding);
        return submitFromData;
    }

    /**
     * 数据提交 提交到后台
     *
     * @param
     * @return 返回报文 map
     */
    public static Map<String, String> submitUrl(
            Map<String, String> submitFromData, String requestUrl) {
        String resultString = "";
        System.out.println("requestUrl====" + requestUrl);
        System.out.println("submitFromData====" + submitFromData.toString());
        /**
         * 发送
         */
        HttpClient hc = new HttpClient(requestUrl, 30000, 30000);
        try {
            int status = hc.send(submitFromData, encoding);
            if (200 == status) {
                resultString = hc.getResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> resData = new HashMap<String, String>();
        /**
         * 验证签名
         */
        if (null != resultString && !"".equals(resultString)) {
            // 将返回结果转换为map
            resData = SDKUtil.convertResultStringToMap(resultString);
            boolean validate = SDKUtil.validate(resData, encoding);
            Assert.isTrue(validate, SystemError.PAY_22005);
            System.out.println("验证签名成功");
            Assert.isTrue(("00").equals(resData.get("respCode")), SystemError.PAY_22014, resData.get("respMsg"));
            // 打印返回报文
            System.out.println("打印返回报文：" + resultString);
        }
        return resData;
    }
}
